package com.cloudptt.api.product.update;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.core.content.FileProvider;

import com.cloudptt.api.comm.CommDlg;
import com.cloudptt.api.comm.Common;
import com.cloudptt.api.comm.FileOperation;
import com.cloudptt.api.models.VersionInfo;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.ProductConst;
import com.cloudptt.api.product.device.DeviceInfo;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.res.Resource;
/**
 *@author coolszy
 *@date 2012-4-26
 *@blog http://blog.92coding.com
 */

public class UpdateManager implements CheckResultListener
{
//	private final static String THIS_FILE = "UpdateManager";

	private static final String action = "android.intent.action.command" ;
	private final static String CMD_STR = "system/bin/pm install -r ";
	private VersionInfo versionInfo = null;

	public static final int GetVERSION = 0;
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;
	/* 更新进度条 */
	//	private ProgressDialog mProgress;
	private ProgressDialog mDownloadDialog;
	private boolean isTip = true;
	private String otaHttpUrl = null;
	private int versionCode = 0;
//	private boolean isAuto = false;

	private String versionPath = null;
	private UpdateListener listener = null;
	private int type = ProductConst.ProductType_PAPP;

	private Handler mHandler = new Handler(Looper.getMainLooper())
	{
		public void handleMessage(Message msg)
		{
//			Log.d(THIS_FILE, "handleMessage msg.what = " + msg.what);
			switch (msg.what)
			{
			case GetVERSION:
				versionInfo = (VersionInfo)msg.obj;
				Log.debug(this.getClass(), "handleMessage versionInfo = " + versionInfo);
				if(versionInfo == null)
				{
					String errStr = Resource.getString("soft_updat_failed");
					CommDlg.showToast(mContext, errStr);
					return;
				}
				
				boolean isUpdate = checkUpdate(versionInfo);
				if(isUpdate)
				{
					listener.onUpdate(UpdateListener.UpdateDownload);
				}
//				else if(isMust)
//				{
//					listener.onUpdate(UpdateListener.UpdateCancel);
//				}
				break;
				// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
//				listener.setUpdate(true);
				mDownloadDialog.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				listener.onUpdate(UpdateListener.UpdateInstall);
				// 安装文件
//				if(isAuto)
//				{
//					autoInstall();
//				}
//				else
//				{
				newInstallApk();
//				}
				break;
			default:
				break;
			}
		};
	};

		/*<?xml version="1.0" encoding="UTF-8"?>
		<info>
			<version>2</version>
			<name>IAS_APP_V21.01</name>
			<url>http://xxx/xxx/xxx/IAS_APP.apk</url>
			<must>1</must><!--1:must 0:warring-->
			<info>修改内容:xxxxxxxxxx</info>
		</info>*/
	public UpdateManager(Context context,String url,int versionCode,boolean tip,String otaHttpUrl,UpdateListener listener)
	{
		Log.debug(this.getClass(),"UpdateManager url = " + url + " versionCode is " + versionCode);
		this.mContext = context;
		this.versionPath = url;
		this.versionCode = versionCode;
		this.isTip = tip;
		this.otaHttpUrl = otaHttpUrl;
		this.listener = listener;
	}

	public void runCheckThread()
	{
//		listener.setUpdate(true);
		String sdpath = Environment.getExternalStorageDirectory() + "/";
		File path = new File(sdpath);
		FileOperation.deletAllFile(path,FileOperation.KeyType_End,".apk");
		
		ParseVersionInfo check = new ParseVersionInfo();
		Log.debug(this.getClass(),"runCheckThread versionPath = " + versionPath);
		check.doCheckVersion(versionPath,this);
	}

	/**
	 * 检测软件更新
	 */
	public boolean checkUpdate(VersionInfo versionInfo)
	{
		if (isUpdate())
		{
			// 显示提示对话框
			if(versionInfo.isMust())
			{
				showDownloadDialog();
			}
			else
			{
				showNoticeDialog();
			}
			return true;
		} 
		else
		{
			if(isTip)
			{
				String str = Resource.getString("soft_update_no");
				CommDlg.showShortToast(mContext, str);
			}
			return false;
		}
	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate()
	{
		// 获取当前软件版本
		if (null != versionInfo)
		{
			Log.debug(this.getClass(), "isUpdate versionCode = " + versionCode);
			Log.debug(this.getClass(), "isUpdate VersionInfo = " + versionInfo.toString());
			int serviceCode = versionInfo.getVersionCode();
			// 版本判断
			if (serviceCode > versionCode)
			{
				return true;
			}
		}
		return false;
	}

	/**
	 * 显示软件更新对话框
	 */
	private void showNoticeDialog()
	{
		// 构造对话框
		AlertDialog.Builder builder = new Builder(mContext);
		String str = Resource.getString("soft_update_title");
		builder.setTitle(str);
		str = Resource.getString("soft_update_info");
		builder.setMessage(str);
		builder.setCancelable(false);
		// 更新
		str = Resource.getString("soft_update_updatebtn");
		builder.setPositiveButton(str, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				// 显示下载对话框
				showDownloadDialog();
			}
		});
		if(!versionInfo.isMust())
		{
			// 稍后更新
			str = Resource.getString("soft_update_later");
			builder.setNegativeButton(str, new OnClickListener()
			{
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					listener.onUpdate(UpdateListener.UpdateCancel);
					dialog.dismiss();
				}
			});
		}
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog()
	{
		// 构造软件下载对话框
		mDownloadDialog = new ProgressDialog(mContext);  

		mDownloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
		mDownloadDialog.setIcon(android.R.drawable.progress_indeterminate_horizontal);  
		String str = Resource.getString("soft_updating");
		mDownloadDialog.setMessage(str);  
		mDownloadDialog.setCancelable(false);  
		mDownloadDialog.show();
		// 现在文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk()
	{
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	@Override
	public void onCheckResult(boolean isSuc, VersionInfo info) {
		Log.debug(this.getClass(), "onCheckResult isSuc = " + isSuc + " info = " + info);
		if(isSuc && info != null)
		{
			Message msg = mHandler.obtainMessage(UpdateManager.GetVERSION);
			msg.obj = info;
			msg.sendToTarget();
		}
		else
		{
			Message msg = mHandler.obtainMessage(UpdateManager.GetVERSION);
			msg.obj = null;
			msg.sendToTarget();
		}
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 *@date 2012-4-26
	 *@blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread
	{
		@Override
		public void run()
		{
			try
			{
				if(!Product.mPermissonGrant){
					return;
				}
					// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					// 获得存储卡的路径
					String sdpath = FileOperation.getVersionPath();
					mSavePath = sdpath;// + "download";
					String urlStr = otaHttpUrl +  versionInfo.getUrl();
					Log.debug(this.getClass(), "downloadApkThread urlStr = " + urlStr + " mSavePath = " + mSavePath);
					if(urlStr == null
							|| urlStr.equals(""))
					{
						return;
					}

					URL url = new URL(urlStr);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists())
					{
						file.mkdir();
					}
					File apkFile = new File(mSavePath, versionInfo.getFileName());
					if (!apkFile.exists())
					{
						file.delete();
					}
					Log.debug(this.getClass(), "downloadApkThread begin apkFile = " + apkFile);
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do
					{
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0)
						{
							// 下载完成
						    mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e)
			{
				listener.onUpdate(UpdateListener.UpdateCancel);
				e.printStackTrace();
			} catch (IOException e)
			{
				listener.onUpdate(UpdateListener.UpdateCancel);
				e.printStackTrace();
			}
			Log.debug(this.getClass(), "downloadApkThread end");
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	private void newInstallApk()
	{
		String apkFileStr = mSavePath + versionInfo.getFileName();
		Log.debug(this.getClass(),"newInstallApk mSavePath = " + mSavePath + " getName = " + versionInfo.getFileName());
		File apkFile = new File(apkFileStr);
		Log.debug(this.getClass(), "newInstallApk mSavePath = " + apkFile.getPath());
		if (!apkFile.exists())
		{
			Log.debug(this.getClass(), "newInstallApk return");
			return;
		}

		InstallUtil.installApk(mContext, apkFile);
	}

	/**
	 * 安装APK文件
	 */
	private void installApk()
	{
		String apkFileStr = mSavePath + versionInfo.getFileName();
		Log.debug(this.getClass(), "installApk mSavePath = " + mSavePath + " getName = " + versionInfo.getFileName());
		File apkFile = new File(apkFileStr);
		Log.debug(this.getClass(), "installApk 2 mSavePath = " + apkFile.getPath());
		if (!apkFile.exists())
		{
			return;
		}
		// 通过Intent安装APK文件
		Intent i = null;
		//i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			i = new Intent(Intent.ACTION_VIEW);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			//File apkFile = new File("ias.apk");
			//Log.d(THIS_FILE, "installApk 1 mSavePath = " + apkFile.getPath());
			Uri uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
			i.setDataAndType(uri, "application/vnd.android.package-archive");
		} else {

			i = new Intent(Intent.ACTION_VIEW);
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			i.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
		}
		if(i != null) {
			mContext.startActivity(i);
		}

		android.os.Process.killProcess(android.os.Process.myPid());
	}

//	public boolean autoInstall2() {
//		String apkPath = mSavePath + "/" + versionInfo.getFileName();
//		Process process = null;
//		try {
//			String cmd = CMD_STR + apkPath;
//			process = Runtime.getRuntime().exec(cmd);
//			process.waitFor();
//		} catch (Exception e) {
//			return false;
//		} finally {
//			try {
//				process.destroy();
//			} catch (Exception e) {
//			}
//		}
//		return true;
//	}
	
    

//	private String autoInstall()
//	{
//		if(DeviceInfo.getInfo().isSupportAutoUpdate())
//		{
//			return autoInstallForQ726();
//		}
//		else
//		{
//			sendCmdBroadcast();
//			return "";
//		}
//	}
	
//	private void sendCmdBroadcast()
//	{
//		String apkPath = mSavePath + versionInfo.getName();
//		String command = "system/bin/pm install -r "+apkPath;
//
//		Intent intent = new Intent();
//		intent.setAction(action);
//		intent.putExtra( "command", command);
//		mContext.sendBroadcast(intent);
//	}
//	private boolean isQ728()
//	{
//		String brand = android.os.Build.BRAND;
//		String device = android.os.Build.DEVICE;
//		if(brand == null
//				|| device == null)
//		{
//			return false;
//		}
//		
//		 Log.d("readCalibrateValue", "setspeakeron brand : " +brand );
//		 
//		if((brand.equals( "MACOOX" )
//				|| brand.equals( "K-Micheer" ))&&
//				(device.equals( "Q726" )|| device.equals( "Q726TW" )))
//		{
//			return true;
//		}
//		return false;
//	}

//	private String autoInstallForQ726()
//	{
//		Log.d(THIS_FILE, "autoInstall begin");
//		String apkPath = mSavePath + versionInfo.getName();
//		String[] args = { "pm", "install", "-r", apkPath };
////		String command = "system/bin/pm install -r "+apkPath;
//		Process process=null;
//		InputStream errIs=null;
//		InputStream inIs=null;
//		String result="";
//		try {
//			process=new ProcessBuilder(args).start();
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			int read = -1; errIs=process.getErrorStream();
//			while((read=errIs.read())!=-1)
//			{
//				baos.write(read);
//			}
//			inIs=process.getInputStream();
//			while((read=inIs.read())!=-1)
//			{
//				baos.write(read);
//			}
//			result=new String(baos.toByteArray());
//			if(inIs!=null)
//				inIs.close();
//			if(errIs!=null)
//				errIs.close();
//			process.destroy();
//			}
//		catch (IOException e)
//		{
//			result=e.getMessage();
//		}
//		Log.d(THIS_FILE, "autoInstall end result = " + result);
//		return result;
//	}

//	private boolean autoInstall_old()
//	{
//		String apkPath = mSavePath + "/" + versionInfo.getName();
//		String[] args = { "pm", "install", "-r", apkPath };
//		String result = "";
//		ProcessBuilder processBuilder = new ProcessBuilder(args);
//		Process process = null;
//		InputStream errIs = null;
//		InputStream inIs = null;
//		try {
//			ByteArrayOutputStream baos = new ByteArrayOutputStream();
//			int read = -1;
//			process = processBuilder.start();
//			errIs = process.getErrorStream();
//			while ((read = errIs.read()) != -1) {
//				baos.write(read);
//			}
//			baos.write('\n');
//			inIs = process.getInputStream();
//			while ((read = inIs.read()) != -1) {
//				baos.write(read);
//			}
//			byte[] data = baos.toByteArray();
//			result = new String(data);
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (errIs != null) {
//					errIs.close();
//				}
//				if (inIs != null) {
//					inIs.close();
//				}
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//			if (process != null) {
//				process.destroy();
//			}
//		}
//		if(result != null
//				&& result.toLowerCase().contains("success"))
//		{
//			return true;
//		}
//		return false;
//	}

//	private boolean autoInstallHasRoot()
//	{
//		String apkPath = mSavePath + "/" + versionInfo.getName();
//		Log.d(THIS_FILE, "autoInstall apkPath = " + apkPath);
//		PrintWriter PrintWriter = null;
//		Process process = null;
//		try {
//			process = Runtime.getRuntime().exec("su ");
//			PrintWriter = new PrintWriter(process.getOutputStream());
//			PrintWriter.println("chmod 777 "+apkPath);
//			PrintWriter.println("export LD_LIBRARY_PATH=/vendor/lib:/system/lib");
//			PrintWriter.println("pm install -r "+apkPath);
//			//				          PrintWriter.println("exit");
//			PrintWriter.flush();
//			PrintWriter.close();
//			int value = process.waitFor();
//			Log.d(THIS_FILE, "autoInstall reuslt is " + value);
//			return returnResult(value);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}finally{
//			if(process!=null){
//				process.destroy();
//			}
//		}
//		return false;
//	}

	private boolean returnResult(int value){
		// 代表成功  
		if (value == 0) {
			String str = Resource.getString("soft_updat_suc");
			CommDlg.showShortToast(mContext, str);
			return true;
		} 
		String str = Resource.getString("soft_updat_failed") + value;
		CommDlg.showShortToast(mContext, str);
		return false;
	}
}
